package com.lrkj.waitress.service.impl;

import com.lrkj.common.constant.PropertyConstants;
import com.lrkj.common.exception.BaseException;
import com.lrkj.common.utils.StringUtils;
import com.lrkj.common.utils.bean.BeanUtils;
import com.lrkj.common.utils.uuid.IdUtils;
import com.lrkj.phone.domain.AppUser;
import com.lrkj.phone.service.IAppUserService;
import com.lrkj.phone.service.PhoneLoginService;
import com.lrkj.property.domain.Community;
import com.lrkj.property.domain.Room;
import com.lrkj.property.domain.RoomAuth;
import com.lrkj.property.service.ICommunityService;
import com.lrkj.property.service.IRoomAuthService;
import com.lrkj.property.service.IRoomService;
import com.lrkj.property.vo.RoomAuthVo;
import com.lrkj.waitress.domain.CustomInfo;
import com.lrkj.waitress.domain.RoomCustom;
import com.lrkj.waitress.mapper.RoomCustomMapper;
import com.lrkj.waitress.service.ICustomInfoService;
import com.lrkj.waitress.service.IRoomCustomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 房屋业主关系Service业务层处理
 *
 * @author yajun_ren
 * @date 2022-03-17
 */
@Service
public class RoomCustomServiceImpl implements IRoomCustomService {
    @Autowired
    private RoomCustomMapper roomCustomMapper;

    @Autowired
    private IRoomService roomService;

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private ICustomInfoService customInfoService;

    @Autowired
    private IAppUserService appUserService;

    @Autowired
    private PhoneLoginService phoneLoginService;

    @Autowired
    private IRoomAuthService roomAuthService;


    /**
     * 查询房屋业主关系列表
     *
     * @param roomCustom 房屋业主关系
     * @return 房屋业主关系
     */
    @Override
    public List<RoomCustom> selectRoomCustomList(RoomCustom roomCustom) {
        return roomCustomMapper.selectRoomCustomList(roomCustom);
    }

    @Override
    public int insertRoomCustom(RoomCustom roomCustom) {
        return roomCustomMapper.insertRoomCustom(roomCustom);
    }

    @Override
    public int updateRoomCustom(RoomCustom roomCustom) {
        return roomCustomMapper.updateRoomCustom(roomCustom);
    }

    /**
     * 批量删除房屋业主关系
     *
     * @param roomIds 需要删除的房屋业主关系ID
     * @return 结果
     */
    @Override
    public int deleteRoomCustomByIds(String[] roomIds) {
        return roomCustomMapper.deleteRoomCustomByIds(roomIds);
    }

    /**
     * 删除房屋业主关系信息
     *
     * @param roomId 房屋业主关系ID
     * @return 结果
     */
    @Override
    public int deleteRoomCustomById(String roomId) {
        return roomCustomMapper.deleteRoomCustomById(roomId);
    }

    @Override
    @Transactional
    public int doSavaOrUpdate(RoomCustom roomCustom) {
        Room room = roomService.selectRoomById(roomCustom.getRoomId());
        //查询业主ID是否存在
        if (null == roomCustom.getCustomId()) {
            String customId = IdUtils.simpleUUID();
            //没有查询到业主,新增一条业主信息
            Community community = communityService.selectCommunityById(room.getCommunityId());
            CustomInfo customInfo = new CustomInfo();
            customInfo.setCustomId(customId);
            customInfo.setCustomType(PropertyConstants.custom_type_10);//客户类别
            customInfo.setCommunityId(room.getCommunityId());
            customInfo.setCustomName(roomCustom.getCustomName());
            customInfo.setDeptId(room.getDeptId());
            customInfo.setAncestors(community.getAncestors() + "," + community.getId());
            customInfo.setCellPhoneNumber(roomCustom.getCellPhoneNumber());
            customInfo.setIdCard(roomCustom.getIdCard());
            customInfo.setSex("2");
            customInfo.setAppUserId(roomCustom.getAppUserId());
            customInfoService.insertCustomInfo(customInfo);
            roomCustom.setCustomId(customId);
        }
        //如果是手机端认证
        if(roomCustom.getWrVerify().equals(PropertyConstants.WR_VERIFY_Y)){
            CustomInfo customInfo = customInfoService.selectCustomInfoById(roomCustom.getCustomId());
            customInfo.setAppUserId(customInfo.getAppUserId());
            customInfoService.updateAppUserId(customInfo);
        }
        RoomCustom oldRoomCustom = roomCustomMapper.selectByRoomIdAndCustomId(roomCustom.getRoomId(), roomCustom.getCustomId());
        if (null != oldRoomCustom) {
            roomCustomMapper.updateRoomCustom(roomCustom);
        } else {
            roomCustomMapper.insertRoomCustom(roomCustom);
        }
        return 1;
    }

    @Override
    public Map<String, Object> appUserRoomAuth(RoomAuthVo roomAuth) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", "100");
        result.put("msg", "认证成功");
        if (!phoneLoginService.verifyCode(roomAuth.getCellPhoneNumber() + "", roomAuth.getPhoneCode())) {
            throw new BaseException("验证码错误或已失效,请重新发送验证码");
        }
        Room room = roomService.selectRoomById(roomAuth.getRoomId());
        //检查房间是否绑定了业主
        if (StringUtils.isEmpty(room.getOwnerId())) {
            throw new BaseException("认证失败:未查询到房间的业主人员信息。");
        }

        //app用户信息
        AppUser appUser = appUserService.selectAppUserByUserName(roomAuth.getCellPhoneNumber() + "");
        if (null == appUser) {
            throw new BaseException("认证失败:手机号码与当前登录用户信息不符。");
        }

        //检查客户表当前APP用户手机号是否存在
        CustomInfo ciEg = new CustomInfo();
        ciEg.setCellPhoneNumber(roomAuth.getCellPhoneNumber() + "");//手机号码
        ciEg.setCommunityId(roomAuth.getCommunityId());//小区ID
        List<CustomInfo> customInfos = customInfoService.selectCustomInfoList(ciEg);
        if (null != customInfos && customInfos.size() > 0) {
            CustomInfo customInfo = customInfos.get(0);
            if (roomAuth.getOwnerType().equals(PropertyConstants.owner_type_cd_1001)) {
                if (!room.getOwnerId().equals(customInfo.getCustomId())) {
                    throw new BaseException("认证失败:客户信息与房屋入住业主信息不一致。。");
                }
            } else if (roomAuth.getOwnerType().equals(PropertyConstants.owner_type_cd_1003)) {
                if (!room.getOwnerId().equals(customInfo.getCustomId())) {
                    throw new BaseException("认证失败:租户信息与房屋租户信息不一致。。");
                }
            }
            //检查是客户是否和房屋有绑定关系
            RoomCustom roomCustom = roomCustomMapper.selectByRoomIdAndCustomId(roomAuth.getRoomId(), customInfo.getCustomId());

            //认证房屋信息 ， 如果是之前添加的家庭成员,只需要更新认证状态
            if (null != roomCustom) {
                if (roomCustom.getWrVerify().equals(PropertyConstants.WR_VERIFY_Y)) {
                    throw new BaseException("认证失败:房间已经认证过,无需再次认证。");
                }
                if (!customInfo.getCustomName().equals(roomAuth.getCustomName())) {
                    throw new BaseException("认证失败:客户姓名和入住时填写的客户姓名不一致。");
                }
                if (StringUtils.isNotEmpty(roomAuth.getIdCard()) && !customInfo.getIdCard().equals(roomAuth.getIdCard())) {
                    throw new BaseException("认证失败:身份证号和入住时填写的身份证号不一致。");
                }
                roomCustom.setWrVerify(PropertyConstants.WR_VERIFY_Y);
                roomCustomMapper.updateRoomCustom(roomCustom);
                customInfo.setAppUserId(appUser.getAppUserId());
                customInfoService.updateAppUserId(customInfo);//更新APP用户ID
            } else {
                if (roomAuth.getOwnerType().equals(PropertyConstants.owner_type_cd_1001)) {
                    throw new BaseException("认证失败:请前往物业公司,办理入伙登记。");
                } else if (roomAuth.getOwnerType().equals(PropertyConstants.owner_type_cd_1003)) {
                    throw new BaseException("认证失败:没有查询到租户信息。");
                } else {
                    //家庭成员|租户并且没有绑定过房屋的 认证需要审批
                    this.createRoomAuth(roomAuth, customInfo, appUser, room);
                    result.put("code", "101");
                    result.put("msg", "当前房间需要等待审批");
                }
            }
        } else {
            if (roomAuth.getOwnerType().equals(PropertyConstants.owner_type_cd_1002)) {
                //家庭成员|租户并且没有绑定过房屋的 认证需要审批
                this.createRoomAuth(roomAuth, new CustomInfo(), appUser, room);
            } else {
                throw new BaseException("认证失败:未查询到房间的入住人员信息。");
            }
        }
        return result;
    }

    //创建房屋认证审批记录
    public void createRoomAuth(RoomAuthVo roomAuth, CustomInfo customInfo, AppUser appUser, Room room) {
        //家庭成员|租户并且没有绑定过房屋的 认证需要审批
        RoomAuth authBean = new RoomAuth();
        BeanUtils.copyBeanProp(authBean, roomAuth);
        authBean.setAppUserId(appUser.getAppUserId());
        authBean.setStatus(PropertyConstants.room_auth_status_10);
        authBean.setRoomOwnerId(room.getOwnerId());
        authBean.setRoomName(room.getRoomName());
        authBean.setCommunityName(room.getCommunityName());
        authBean.setCustomId(customInfo.getCustomId());//客户ID
        roomAuthService.insertRoomAuth(authBean);
    }

    @Override
    public int roomDefault(RoomCustom roomCustom) {
        //重置用户名下房屋默认选中状态
        roomCustomMapper.resetDefaultStatus(roomCustom.getCustomId());
        RoomCustom oldBean = roomCustomMapper.selectByRoomIdAndCustomId(roomCustom.getRoomId(), roomCustom.getCustomId());
        if (null != oldBean) {
            oldBean.setWrDefault(PropertyConstants.WR_VERIFY_Y);
        }
        return roomCustomMapper.updateRoomCustom(oldBean);
    }

    @Override
    public List<Map<String, Object>> appUserCommunityList(String appUserId) {
        return roomCustomMapper.appUserCommunityList(appUserId);
    }

    @Override
    public int delRoomBind(RoomCustom roomCustom) {
        RoomCustom oldBean = roomCustomMapper.selectByRoomIdAndCustomId(roomCustom.getRoomId(), roomCustom.getCustomId());
        if (null != oldBean) {
            oldBean.setWrVerify(PropertyConstants.WR_VERIFY_N);
        }
        return roomCustomMapper.updateRoomCustom(oldBean);
    }


    /**
     * 批量新增房屋业主关系信息
     *
     * @param roomCustoms 房屋业主关系对象
     */
    public int batchAddData(List<RoomCustom> roomCustoms) {
        return roomCustomMapper.batchAddData(roomCustoms);
    }
}
